package interview.volatiled;
/**
 *
 * 验证volatile不保证原子性
 *
 * */

class Resource{

    public  volatile int number=0;

    public   void add(){
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        this.number++;
    }
}

public class VolatileDemo2 {

    public static void main(String[] args) {
        Resource resource = new Resource();

        for(int i=0;i<20;i++){

            new Thread(()->{
                System.out.println(Thread.currentThread().getName());
                for(int j=0;j<100;j++){
                    resource.add();
                }

            },String.valueOf(i)).start();

        }
        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println("number="+resource.number);
    }


}
